﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Elderlyhealth.DAL; // 引入你的数据层命名空间

public partial class people : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (Session["CustomerId"] != null && Session["UserType"]?.ToString() == "Relative")
            {
                lblWelcome.Text = "欢迎您, " + Session["CustomerName"].ToString();
                LoadUserInfo();
                LoadNotificationSettings();
                LoadNotifications(); // 加载系统通知
            }
            else
            {
                Response.Redirect("~/Login.aspx");
            }
        }
    }
    private void LoadNotifications()
    {
        int userId = Convert.ToInt32(Session["CustomerId"]);

        using (var db = new DataClasses1DataContext())
        {
            // 假设 TNotifications 表存储所有系统通知
            var notifications = (from n in db.TNotifications
                                 where n.UserId == userId
                                 orderby n.Timestamp descending
                                 select new
                                 {
                                     Message = n.Message,
                                     Timestamp = n.Timestamp
                                 }).Take(5).ToList();

            // 在查询结果中对 Timestamp 进行格式化
            var formattedNotifications = notifications.Select(n => new
            {
                Message = n.Message,
                Timestamp = n.Timestamp.HasValue ? n.Timestamp.Value.ToString("yyyy-MM-dd HH:mm") : ""
            }).ToList();

            rptNotifications.DataSource = formattedNotifications;
            rptNotifications.DataBind();
        }
    }
    private void LoadNotificationSettings()
    {
        int userId = Convert.ToInt32(Session["CustomerId"]);

        using (var db = new DataClasses1DataContext())
        {
            var settings = db.TNotificationSettings.SingleOrDefault(s => s.UserId == userId);
            if (settings != null)
            {
                cbHealthAlert.Checked = settings.HealthAlert;
                cbBindingRequest.Checked = settings.BindingRequest;
                cbSystemUpdates.Checked = settings.SystemUpdates;
            }
        }
    }
    private void LoadUserInfo()
    {
        int userId = Convert.ToInt32(Session["CustomerId"]);

        using (var db = new DataClasses1DataContext())
        {
            // 从子女表加载用户信息
            var relativeInfo = db.Trelative子女.SingleOrDefault(r => r.子女id == userId);
            if (relativeInfo != null)
            {
                txtName.Text = relativeInfo.名字;
                txtPhone.Text = relativeInfo.电话;
                txtPwd.Text = relativeInfo.密码;
                txtEmail.Text = relativeInfo.邮箱;
            }
        }
    }
    protected void btnBindOld_Click(object sender, EventArgs e)
    {
        int relativeId = Convert.ToInt32(Session["CustomerId"]);
        int oldId;

        if (int.TryParse(txtOldId.Text.Trim(), out oldId))
        {
            using (var db = new DataClasses1DataContext())
            {
                var existingOld = db.Tolder老人.SingleOrDefault(o => o.old_id == oldId);
                if (existingOld != null)
                {
                    var existingMapping = db.RelativeOldMapping.SingleOrDefault(
                        m => m.子女id == relativeId && m.老人id == oldId && m.审核状态 == false);

                    if (existingMapping == null)
                    {
                        RelativeOldMapping newMapping = new RelativeOldMapping
                        {
                            子女id = relativeId,
                            老人id = oldId,
                            审核状态 = false,
                            绑定时间 = DateTime.Now
                        };
                        db.RelativeOldMapping.InsertOnSubmit(newMapping);
                        db.SubmitChanges();

                        lblMsg.Text = "绑定申请已提交，等待管理员审核。";
                    }
                    else
                    {
                        lblMsg.Text = "您已经提交了该老人的绑定申请，请等待管理员审核。";
                    }
                }
                else
                {
                    lblMsg.Text = "无效的老人 ID。";
                }
            }
        }
        else
        {
            lblMsg.Text = "请输入有效的老人 ID。";
        }
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        int userId = Convert.ToInt32(Session["CustomerId"]);

        using (var db = new DataClasses1DataContext())
        {
            var relativeInfo = db.Trelative子女.SingleOrDefault(r => r.子女id == userId);
            if (relativeInfo != null)
            {
                relativeInfo.名字 = txtName.Text.Trim();
                relativeInfo.电话 = txtPhone.Text.Trim();
                relativeInfo.密码 = txtPwd.Text.Trim();
                relativeInfo.邮箱 = txtEmail.Text.Trim();

                db.SubmitChanges();
                lblUpdateMsg.Text = "信息更新成功！";
            }
            else
            {
                lblUpdateMsg.Text = "用户信息更新失败，请稍后再试。";
            }
        }
    }

    protected void btnSaveNotifications_Click(object sender, EventArgs e)
    {
        int userId = Convert.ToInt32(Session["CustomerId"]);

        using (var db = new DataClasses1DataContext())
        {
            var settings = db.TNotificationSettings.SingleOrDefault(s => s.UserId == userId);

            if (settings != null)
            {
                settings.HealthAlert = cbHealthAlert.Checked;
                settings.BindingRequest = cbBindingRequest.Checked;
                settings.SystemUpdates = cbSystemUpdates.Checked;
            }
            else
            {
                // 如果没有现有记录，则创建一个新记录
                settings = new TNotificationSettings
                {
                    UserId = userId,
                    HealthAlert = cbHealthAlert.Checked,
                    BindingRequest = cbBindingRequest.Checked,
                    SystemUpdates = cbSystemUpdates.Checked
                };
                db.TNotificationSettings.InsertOnSubmit(settings);
            }

            db.SubmitChanges();
            lblNotificationMsg.Text = "通知设置已更新！";
        }
    }
}

